package com.hnx.admin.aurora.core.jwt;

import com.hnx.admin.aurora.jwt.api.JwtFilter;
import com.hnx.admin.aurora.jwt.config.JwtUtil;
import com.hnx.admin.aurora.redis.RedisCache;
import com.hnx.admin.aurora.security.utils.SecurityUtil;
import com.hnx.admin.aurora.system.domain.vo.user.entity.UserDetailVO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class AdminJwtTokenFilter implements JwtFilter {
    private final JwtUtil jwtUtil;
    private final RedisCache redisCache;

    @Override
    public void match(HttpServletRequest request) {
        String userKey = jwtUtil.getUserKey(request);
        if (StringUtils.hasText(userKey)) {
            UserDetailVO loginUser = redisCache.getCacheObject(userKey, UserDetailVO.class);
            if (Objects.nonNull(loginUser) && Objects.isNull(SecurityUtil.getAuthentication())) {
                String token = jwtUtil.getToken(request);
                jwtUtil.validToken(token,loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
    }
}
